import axios from "axios";
import { ACCESS_TOKEN } from "@/store/mutation-types";
//获取用户相关仓库
import useUserStore from "@/store/modules/user";
let userStore: any = null;
//baseUrl
const apiBaseUrl = import.meta.env.VITE_APP_API_BASE_URL || "";

//初始化http类
const request = axios.create({
  baseURL: apiBaseUrl, // 所有的请求地址前缀部分(没有后端请求不用写)
  timeout: 80000, // 请求超时时间(毫秒)
  withCredentials: true, // 异步请求携带cookie
  headers: {
    "X-Requested-With": "XMLHttpRequest",
  },
});

//请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加全局的loading..
    // 请求头携带token
    if (userStore == null) {
      userStore = useUserStore();
    }
    const token = userStore.token_computed;
    if (token) {
      config.headers[ACCESS_TOKEN] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    }

    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

//响应拦截
request.interceptors.response.use(
  (res) => {
    //返回数据
    const { data } = res;
    console.log("返回数据处理", res);
    return data;
  },
  (error: any) => {
    console.log("error==>", error);
    return Promise.reject(error);
  }
);

export default request;
